package com.rental.houses.config;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.core.type.TypeReference;
import com.rental.model.vo.house.RequiredHouseVo;

import java.io.IOException;
import java.util.List;

public class IPageDeserializer extends StdDeserializer<IPage<?>> {

    private static final long serialVersionUID = 1L;
    private final ObjectMapper objectMapper = new ObjectMapper();

    public IPageDeserializer() {
        this(null);
    }

    public IPageDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public IPage<?> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        JsonNode node = p.getCodec().readTree(p);
        Long current = node.get("current").asLong();
        Long size = node.get("size").asLong();
        Long total = node.get("total").asLong();

        // 使用 TypeReference 指定具体的类型
        TypeReference<List<RequiredHouseVo>> typeRef = new TypeReference<List<RequiredHouseVo>>() {};
        List<RequiredHouseVo> records = objectMapper.convertValue(node.get("records"), typeRef);

        Page<RequiredHouseVo> page = new Page<>(current, size, total);
        page.setRecords(records);

        return page;
    }
}
